/**
 * @Time    : 2022/03/09 15:19
 * @Author  : WanRongJia
 * @License : Software business license
 * @Site    : www.linshensjl.top
 * @File    : searchUser.js
 * @Software: Rich Web Platform
 * @Function: 用户名登录
 * @Version : 1.0
 **/
const { matchedData } = require('express-validator')
const { findUserByName } = require('./helpers/findUserByName')
const { checkPassword } = require('./helpers/checkPassword')
const { checkUserBlock } = require('./helpers/checkUserBlock')
const { buildResponse } = require('../../utils/buildResponse')
const { handleError } = require('../../utils/handleError');
const { buildJWT } = require('../../utils/buildJWT');
let logger = require('log4js').getLogger("default");
const loginByName = async function (req, res) {
    try {
        const data = matchedData(req)
        // 查询用户信息
        let userInfo = await findUserByName(data.user_name)
        await checkUserBlock(userInfo)
        //验证密码
        const isPasswordMatch = await checkPassword(data.password, userInfo)
        if (!isPasswordMatch) {
            logger.error('密码错误');
            res.json(buildResponse({}, '错误', false))
            //密码错误后，调用passwordsDoNotMatch方法存储loginAttempts+1
        } else {
            const { user_name, user_code, nick_name, mobile, id } = userInfo
            let data = {
                user_info: {
                    user_name,
                    user_code,
                    nick_name,
                    mobile,
                },
                token: buildJWT({ id, user_code, nick_name })
            }
            res.status(200).json(buildResponse(data, '登录成功', true))
        }
    } catch (err) {
        logger.error(err)
        handleError(res, err)
    }
}

module.exports = { loginByName }